<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <MyHeader :addTodo="addTodo"/>
      <MyList :todos="todos" :delTodo="delTodo" :updateTodo="updateTodo"/>
      <MyFooter :todos="todos" :checkAll="checkAll" :clear="clearAllCompleteTodos"/>
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent, onMounted, reactive, toRefs, watch} from "vue";
import MyHeader from "@/components/MyHeader.vue";
import MyList from "@/components/MyList.vue";
import MyFooter from "@/components/MyFooter.vue";
import {Todo} from "@/commons/todo";
import {saveArray, readArray} from "@/utils/localStorageUtil";

export default defineComponent({
  name: "App",
  components: {
    MyHeader, MyList, MyFooter
  },
  setup() {
    const state = reactive<{ todos: Todo[] }>({
      todos: []
    });

    const key = 'todos_key'

    onMounted(() => {
      state.todos = readArray(key)
    })

    const addTodo = (todo: Todo) => {
      state.todos.unshift(todo)
    }
    const delTodo = (index: number) => {
      state.todos.splice(index, 1)
    }
    const updateTodo = (todo: Todo, isComplete: boolean) => {
      todo.isCompleted = isComplete; // 修改属性, 属性的修改应该让数据存放的地方修改也就是父组件
    }
    const checkAll = (isComplete: boolean) => {
      state.todos.forEach(todo => {
        todo.isCompleted = isComplete
      })
    }
    const clearAllCompleteTodos = () => {
      state.todos = state.todos.filter(todo => !todo.isCompleted)
    }

    watch(state.todos, (todos: Todo[]) => {
      saveArray(key, todos as [])
    }, {deep: true})

    return {
      ...toRefs(state),
      addTodo,
      delTodo,
      updateTodo,
      checkAll,
      clearAllCompleteTodos
    }
  }
})
</script>

<style scoped>
.todo-container {
  width: 600px;
  margin: 0 auto;
}

.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
